package de.uni_saarland.coli.doclists.suffixtree;

import de.uni_saarland.coli.doclists.document.IndexDocument;
import de.uni_saarland.coli.doclists.index.Index;

public class Suffix {
	private IndexDocument doc;

	private int start;
	private int end;

	private int mainNode;

	public Suffix() {
		this.start = 0;
		this.end = 0;
		this.doc = null;
	}

	public void canonize() {
		if (!this.isExplicit()) {
			STreeEdge edge = Index.getEdgeMap().find(this.mainNode,
					this.getToken(this.getStart()));
			if (edge == null) {
				return;
			}

			int edgeSpan = edge.getLastTokenIndex() - edge.getFirstTokenIndex() - 1;


			while (edgeSpan <= (this.end - this.start)) {
				this.start += edgeSpan + 1;
				this.mainNode = edge.getEndNode();
				if (this.start <= this.end) {
					edge = Index.getEdgeMap().find(edge.getEndNode(),
							this.doc.getTermAt(this.start));
					edgeSpan = edge.getLastTokenIndex()
							- edge.getFirstTokenIndex() - 1;
				}
			}
		}
	}

	public void increaseStart() {
		this.start++;
	}

	public void increaseEnd() {
		this.end++;
	}

	public int getDocID() {
		return this.doc.getDocID();
	}

	public int getToken(int pos) {
		return this.doc.getTermAt(pos);
	}

	public boolean isExplicit() {
		return this.start > this.end;
	}

//	public boolean isImplicit() {
//		return this.end >= this.start;
//	}

	public IndexDocument getDoc() {
		return doc;
	}

	public void setDoc(IndexDocument doc) {
		this.doc = doc;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getEnd() {
		return end;
	}

	public void setEnd(int end) {
		this.end = end;
	}

	public int getMainNode() {
		return mainNode;
	}

	public void setMainNode(int mainNode) {
		if (mainNode >= 0)
			this.mainNode = mainNode;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();

		sb.append("SE: " + this.getStart() + " => " + this.getEnd()).append("\n");
		sb.append("suffix: ");
		for (int i = this.getStart(); i < this.getEnd(); i++) {
			sb.append(" ").append(Index.getTermDictionary().getValue(this.doc.getTermAt(i)));
		}
		sb.append("\n");
		return sb.toString();
	}
}
